package com.excesys.exsecs.scada.task;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.excesys.exsecs.access.constant.RedisConstant;
import com.excesys.exsecs.access.entity.DataFlowOperation;
import com.excesys.exsecs.access.service.DataFlowOperationService;
import com.excesys.exsecs.scada.mapper.ScadaSystemMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import static cn.hutool.core.date.DateTime.now;


@Slf4j
@Component
@AllArgsConstructor
public class SystemTask {

	private final ScadaSystemMapper scadaSystemMapper;

	private final StringRedisTemplate redisTemplate;

	private final DataFlowOperationService dataFlowOperationService;

	/**
	 * 天气定时任务
	 */
	@Scheduled(cron = "0 0/5 * * * ?")
	public void weather(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		log.info("天气任务开始时间:"+now());
		// 创建标准的httpClient
		HttpClient client = HttpClients.createDefault();

		try {
			String url = "https://aider.meizu.com/app/weather/listWeather?cityIds=101020100";
			HttpGet get = new HttpGet(url);
			// 执行
			HttpResponse response = client.execute(get);
			//http实例化对象
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity,"UTF-8");
			JSONObject object = JSON.parseObject(result);
			JSONArray array = (JSONArray) object.get("value");
			if(ObjectUtil.isNotNull(array)){
				JSONObject jsonObject  =(JSONObject) array.get(0);
				JSONObject realtime =(JSONObject) jsonObject.get("realtime");
				//获取温度数据
				Float temp = Convert.toFloat( realtime.get("temp"));
				//根据标识查询unitNo
				String unitNo = scadaSystemMapper.selectNoByIdentify("temp");
				JSONObject redisObject = new JSONObject();
				redisObject.put("unitNo",unitNo);
				redisObject.put("system_name","温度");
				Map<String,Object> data = new HashMap<>();
				data.put("temp",temp);
				redisObject.put("data",data);
				redisObject.put("timestamp",sdf.format(new Date().getTime()));
				//更新redis
				redisTemplate.opsForHash().put(RedisConstant.SYSTEM_PROPERTY_LIST,unitNo,redisObject.toString());

				log.info("天气任务结束时间:"+now());
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 温度小时流水
	 */
	//@Scheduled(cron = "0 0 * * * ?")
	public void tempHourFlow(){
		log.info("定时任务：tempHourFlow()开始时间："+now());

		//根据标识查询unitNo
		String unitNo = scadaSystemMapper.selectNoByIdentify("temp");
		Integer count = scadaSystemMapper.checkTableExists("t_" + unitNo);
		if(count == 0){
			dataFlowOperationService.createCustomTable("t_"+unitNo);
			log.info("【温度小时流水表】：【t_"+unitNo+"】建表成功");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		}
		//温度流水入库
		Object obj = redisTemplate.opsForHash().get(RedisConstant.SYSTEM_PROPERTY_LIST, unitNo);
		if(ObjectUtil.isNotNull(obj)&& obj.toString().length()>0){
			JSONObject redisObj = JSON.parseObject(obj.toString());

			DataFlowOperation dataFlowOperation = new DataFlowOperation();
			dataFlowOperation.setTableName("t_"+unitNo);
			dataFlowOperation.setUnitNo(unitNo);
			dataFlowOperation.setData(redisObj.getString("data"));
			dataFlowOperation.setCreateTime(LocalDateTime.parse(redisObj.getString(RedisConstant.TIMESTAMP).replace(" ","T")));

			dataFlowOperationService.executeInsertSql(dataFlowOperation);
		}
		log.info("定时任务：tempHourFlow()结束时间："+now());
	}

}
